package org.jeecg.modules.htxincailiao.analytics.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.contant.HTClient;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.IPInfo;
import org.jeecg.common.util.IPUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.htxincailiao.account.entity.HTPlatformUser;
import org.jeecg.modules.htxincailiao.account.service.IHTAccountService;
import org.jeecg.modules.htxincailiao.analytics.domain.dto.HTGoodsDetailVisitUpdateDTO;
import org.jeecg.modules.htxincailiao.analytics.domain.vo.HTGoodsDetailVisitInfoVO;
import org.jeecg.modules.htxincailiao.analytics.domain.vo.HTGoodsDetailVisitStatisticsVO;
import org.jeecg.modules.htxincailiao.analytics.entity.HTGoodsDetailVisitAction;
import org.jeecg.modules.htxincailiao.analytics.service.IHTGoodsDetailVisitActionService;
import org.jeecg.modules.htxincailiao.area.entity.HTArea;
import org.jeecg.modules.htxincailiao.area.service.IHTAreaService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: ht_goods_detail_visit_action
 * @Author: jeecg-boot
 * @Date: 2022-06-07 10:12:00
 * @Version: V1.0
 */
@Api(tags = "ht_goods_detail_visit_action")
@RestController
@RequestMapping("/analytics/hTGoodsDetailVisitAction")
@Slf4j
public class HTGoodsDetailVisitActionController extends JeecgController<HTGoodsDetailVisitAction, IHTGoodsDetailVisitActionService> {
    @Resource
    private IHTGoodsDetailVisitActionService hTGoodsDetailVisitActionService;


    @Resource
    private IHTAccountService accountService;

    @Resource
    private IHTAreaService areaService;

    /**
     * PV、UV数据查询
     *
     * @param req
     * @param beginTime
     * @param endTime
     * @return
     */
    @AutoLog(value = "ht_goods_detail_visit_action-分页列表查询")
    @ApiOperation(value = "ht_goodsDetail_visit_action-分页列表查询", notes = "ht_goods_detail_visit_action-分页列表查询")
    @GetMapping(value = "/getPVUVData")
    public Result<?> getPVUVData(HttpServletRequest req, String beginTime, String endTime) {
        List<HTGoodsDetailVisitInfoVO> list = hTGoodsDetailVisitActionService.getPVUVData(beginTime, endTime);
        return Result.OK(list);
    }

    /**
     * PV、UV数据查询
     *
     * @param req
     * @param beginTime
     * @param endTime
     * @return
     */
    @AutoLog(value = "ht_goodsDetail_visit_action-分页列表查询")
    @ApiOperation(value = "ht_goods_detail_visit_action-分页列表查询", notes = "ht_goods_detail_visit_action-分页列表查询")
    @GetMapping(value = "/getStatistics")
    public Result<?> getStatistics(HttpServletRequest req, String beginTime, String endTime) {
        HTGoodsDetailVisitStatisticsVO vo = hTGoodsDetailVisitActionService.getStatistics(beginTime, endTime);
        return Result.OK(JSONObject.parse(JSONObject.toJSONString(vo)));
    }

    /**
     * 分页列表查询
     *
     * @param hTGoodsDetailVisitAction
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ht_goods_detail_visit_action-分页列表查询")
    @ApiOperation(value = "ht_goods_detail_visit_action-分页列表查询", notes = "ht_goods_detail_visit_action-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HTGoodsDetailVisitAction hTGoodsDetailVisitAction,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HTGoodsDetailVisitAction> queryWrapper = QueryGenerator.initQueryWrapper(hTGoodsDetailVisitAction, req.getParameterMap());
        Page<HTGoodsDetailVisitAction> page = new Page<HTGoodsDetailVisitAction>(pageNo, pageSize);
        IPage<HTGoodsDetailVisitAction> pageList = hTGoodsDetailVisitActionService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param hTGoodsDetailVisitAction
     * @return
     */
    @AutoLog(value = "ht_goods_detail_visit_action-添加")
    @ApiOperation(value = "ht_goods_detail_visit_action-添加", notes = "ht_goods_detail_visit_action-添加")
    @PostMapping(value = "/add")
    public Result<?> add(HttpServletRequest request, @RequestBody HTGoodsDetailVisitAction hTGoodsDetailVisitAction) throws URISyntaxException, IOException {
        String ip = IPUtil.getClientIp(request);
//        String ip = "182.149.201.158";
        IPInfo info = null;
        try {
//           info = IPUtil.getIPInfo("182.149.201.158");
            info = IPUtil.getIPInfo(ip);
        } catch (URISyntaxException ignored) {
        }

        if (oConvertUtils.isNotEmpty(ip)) {
            hTGoodsDetailVisitAction.setVisitIp(ip);
        }

        Result<JSONObject> result = new Result<>();
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = null;
        if (oConvertUtils.isNotEmpty(token)) {
            username = JwtUtil.getUsername(token);
        }

        if (oConvertUtils.isNotEmpty(hTGoodsDetailVisitAction.getClientOsString())) {
            Integer clientOs = HTClient.GetClientOsIndex(hTGoodsDetailVisitAction.getClientOsString());
            hTGoodsDetailVisitAction.setClientOs(clientOs);
        }

        HTPlatformUser user = null;
        if (oConvertUtils.isNotEmpty(username)) {
            user = accountService.queryFrontendUserByUsername(username);
        }

        if (oConvertUtils.isNotEmpty(user)) {
            hTGoodsDetailVisitAction.setUserId(user.getId());
        }

        String provinceName = oConvertUtils.isNotEmpty(info) ? info.getProvinceName() : null;
        if (oConvertUtils.isNotEmpty(provinceName)) {
            List<HTArea> list = areaService.queryByName(provinceName);
            if (!list.isEmpty()) {
                HTArea area = list.stream().findFirst().orElse(null);
                if (oConvertUtils.isNotEmpty(area)) {
                    hTGoodsDetailVisitAction.setProvinceId(area.getId());
                }
            }
        }
        String provinceId = hTGoodsDetailVisitAction.getProvinceId();
        if (oConvertUtils.isNotEmpty(provinceId)) {
            List<HTArea> list = areaService.fuzzyQueryByName(provinceName);
            if (!list.isEmpty()) {
                HTArea area = list.stream().findFirst().orElse(null);
                if (oConvertUtils.isNotEmpty(area)) {
                    hTGoodsDetailVisitAction.setProvinceId(area.getId());
                }
            }
        }

        if (hTGoodsDetailVisitActionService.save(hTGoodsDetailVisitAction)) {
            HTGoodsDetailVisitAction action =
                    hTGoodsDetailVisitActionService.getById(hTGoodsDetailVisitAction.getId());
            JSONObject obj = new JSONObject();
            obj.put("visitInfo", action);
            result.setResult(obj);
        } else {
            result.error500("保存访问日志失败");
        }

        return result;
    }

    /**
     * 编辑
     *
     * @param body 请求参数
     * @return
     */
    @AutoLog(value = "ht_goods_detail_visit_action-编辑")
    @ApiOperation(value = "ht_goods_detail_visit_action-编辑", notes = "ht_goods_detail_visit_action-编辑")
    @RequestMapping(value = "/visitEdit", method = {RequestMethod.POST})
    public Result<?> visitEdit(HttpServletRequest request, @RequestBody String body) throws IOException {
        HTGoodsDetailVisitUpdateDTO dto = JSONObject.parseObject(body, HTGoodsDetailVisitUpdateDTO.class);
        if (oConvertUtils.isNotEmpty(dto.getId())) {
            HTGoodsDetailVisitAction htGoodsDetailVisitAction = hTGoodsDetailVisitActionService.getById(dto.getId());
            //  只更新需要更新的数据即可
            if (oConvertUtils.isNotEmpty(dto.getLeaveTime())) {
                htGoodsDetailVisitAction.setLeaveTime(dto.getLeaveTime());
                hTGoodsDetailVisitActionService.updateById(htGoodsDetailVisitAction);
            }
        }

        return Result.OK("编辑成功!");
    }


    /**
     * 编辑
     *
     * @param dto
     * @return
     */
    @AutoLog(value = "ht_goods_detail_visit_action-编辑")
    @ApiOperation(value = "ht_goods_detail_visit_action-编辑", notes = "ht_goods_detail_visit_action-编辑")
    @PostMapping(value = "/updateAddToCartClickCount")
    public Result<?> updateAddToCartClickCount(@RequestBody HTGoodsDetailVisitUpdateDTO dto) {
        HTGoodsDetailVisitAction htGoodsDetailVisitAction = null;
        if (oConvertUtils.isNotEmpty(dto.getId())) {
            htGoodsDetailVisitAction = hTGoodsDetailVisitActionService.getById(dto.getId());
        }

        if (oConvertUtils.isNotEmpty(htGoodsDetailVisitAction)) {
            Integer count = htGoodsDetailVisitAction.getAddToCartClickCount() + 1;
            htGoodsDetailVisitAction.setAddToCartClickCount(count);
        }

        if (oConvertUtils.isNotEmpty(htGoodsDetailVisitAction)) {
            hTGoodsDetailVisitActionService.updateById(htGoodsDetailVisitAction);
        }

        return Result.OK("更新成功!");
    }

    /**
     * 编辑
     *
     * @param dto
     * @return
     */
    @AutoLog(value = "ht_goods_detail_visit_action-编辑")
    @ApiOperation(value = "ht_goods_detail_visit_action-编辑", notes = "ht_goods_detail_visit_action-编辑")
    @PostMapping(value = "/updateImmediatelyPurchaseClickCount")
    public Result<?> updateImmediatelyPurchaseClickCount(@RequestBody HTGoodsDetailVisitUpdateDTO dto) {
        HTGoodsDetailVisitAction htGoodsDetailVisitAction = null;
        if (oConvertUtils.isNotEmpty(dto.getId())) {
            htGoodsDetailVisitAction = hTGoodsDetailVisitActionService.getById(dto.getId());
        }

        if (oConvertUtils.isNotEmpty(htGoodsDetailVisitAction) && oConvertUtils.isNotEmpty(htGoodsDetailVisitAction.getImmediatelyPurchaseClickCount())) {
            Integer count = htGoodsDetailVisitAction.getImmediatelyPurchaseClickCount() + 1;
            htGoodsDetailVisitAction.setImmediatelyPurchaseClickCount(count);
        }

        if (oConvertUtils.isNotEmpty(htGoodsDetailVisitAction)) {
            hTGoodsDetailVisitActionService.updateById(htGoodsDetailVisitAction);
        }

        return Result.OK("更新成功!");
    }

    /**
     * 编辑
     *
     * @param hTGoodsDetailVisitAction
     * @return
     */
    @AutoLog(value = "ht_goods_detail_visit_action-编辑")
    @ApiOperation(value = "ht_goods_detail_visit_action-编辑", notes = "ht_goods_detail_visit_action-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody HTGoodsDetailVisitAction hTGoodsDetailVisitAction) {
        hTGoodsDetailVisitActionService.updateById(hTGoodsDetailVisitAction);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_goods_detail_visit_action-通过id删除")
    @ApiOperation(value = "ht_goods_detail_visit_action-通过id删除", notes = "ht_goods_detail_visit_action-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        hTGoodsDetailVisitActionService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ht_goods_detail_visit_action-批量删除")
    @ApiOperation(value = "ht_goods_detail_visit_action-批量删除", notes = "ht_goods_detail_visit_action-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hTGoodsDetailVisitActionService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_goods_detail_visit_action-通过id查询")
    @ApiOperation(value = "ht_goods_detail_visit_action-通过id查询", notes = "ht_goods_detail_visit_action-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        HTGoodsDetailVisitAction hTGoodsDetailVisitAction = hTGoodsDetailVisitActionService.getById(id);
        if (hTGoodsDetailVisitAction == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hTGoodsDetailVisitAction);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hTGoodsDetailVisitAction
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HTGoodsDetailVisitAction hTGoodsDetailVisitAction) {
        return super.exportXls(request, hTGoodsDetailVisitAction, HTGoodsDetailVisitAction.class, "ht_goods_detail_visit_action");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HTGoodsDetailVisitAction.class);
    }

}
